package com.tjec.framework.interceptor;

import com.tjec.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ：cjj
 * @date ：Created in 2020/10/16 15:21
 */
public class ESBHandlerInterceptor implements HandlerInterceptor {

    @Value("${ESB.serviceName}")
    private String esbServiceName;

    @Value("${ESB.sourceSystem}")
    private String esbSourceSystem;

    @Value("${ESB.targetSystem}")
    private String esbTargetSystem;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        boolean flag = true;
        String sourceSystem = request.getParameter("sourceSystem");
        String serviceName = request.getParameter("serviceName");
        String targetSystem = request.getParameter("targetSystem");
        String requestId = request.getParameter("requestId");
        if(StringUtils.isBlank(serviceName)||!serviceName.equals(esbServiceName)
                ||StringUtils.isBlank(sourceSystem)||!sourceSystem.equals(esbSourceSystem)
                ||StringUtils.isBlank(targetSystem)||!targetSystem.equals(esbTargetSystem)
                ||StringUtils.isBlank(requestId)){
            flag = false;
            response.addHeader("statusFlag","0");
        }
        return flag;
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView)
            throws Exception {

    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex)
            throws Exception {
    }
}
